<script setup lang="ts">
import { ref } from 'vue'
import CNav from '@/components/CNav.vue'
import { useUserInfoStore } from '@/stores'
import { ImageAddHttp } from '@/utils/index'
import { onLoad } from '@dcloudio/uni-app'
import { postUpdateUserInfo } from '@/api/user'
const nickname = ref('')
const bio = ref('')
const avatar = ref('/static/default-avatar.png')
const cropper_avatar = ref('')
const userInfo = ref(useUserInfoStore().$state.profile)

function myUpload() {
  uni.chooseImage({
    count: 1,
    success: (rst) => {
      // 设置url的值，显示控件
      cropper_avatar.value = rst.tempFilePaths[0]
    },
  })
}

async function onok(ev: { path: string; base64: string }) {
  cropper_avatar.value = ''
  avatar.value = ev.path
  uni.uploadFile({
    url: '/api/uploadfiles',
    name: 'file',
    filePath: ev.path,
    success: (uploadFileRes) => {
      // 上传成功回调
      console.log('文件上传成功:', uploadFileRes)
      if (uploadFileRes.statusCode === 200) {
        // 解析服务器返回的数据
        const responseData = JSON.parse(uploadFileRes.data)
        console.log('服务器返回数据:', responseData)
        if (responseData.code) {
          avatar.value = responseData.data.full_path
        }
      } else {
        console.error('上传失败:', uploadFileRes)
      }
    },
    fail: (error) => {
      console.error('文件上传失败:', error)
    },
  })
}

function oncancel() {
  cropper_avatar.value = ''
}

function renderInfo(options: any) {
  if (options && options.info == 1) {
    nickname.value = userInfo.value?.nickname?.toString() || ''
    bio.value = userInfo.value?.bio?.toString() || ''
    avatar.value = userInfo.value?.avatar?.toString() || ''
  }
}

async function onSubmit() {
  if (
    userInfo.value &&
    nickname.value === userInfo.value.nickname &&
    bio.value === userInfo.value.bio &&
    avatar.value === userInfo.value.avatar
  ) {
    uni.navigateTo({ url: '/pages/profile/profile' })
    return
  }

  const reslut = await postUpdateUserInfo({
    id: userInfo.value!.id,
    nickname: nickname.value,
    avatar: avatar.value,
    bio: bio.value,
  })
  if (reslut.code && userInfo.value) {
    useUserInfoStore().setProfile({
      ...userInfo.value,
      nickname: nickname.value,
      avatar: avatar.value,
      bio: bio.value,
    })
    uni.navigateTo({ url: '/pages/profile/profile' })
  }

  uni.showToast({
    title: '更新成功',
    icon: 'success',
  })
}

function back() {
  uni.navigateBack()
}

onLoad((options) => {
  renderInfo(options)
})
</script>

<template>
  <view class="container">
    <CNav left-text="返回" @left-click="back" title="个人资料" />
    <ksp-cropper
      mode="fixed"
      :width="300"
      :height="300"
      :max-width="1024"
      :max-height="1024"
      :url="cropper_avatar"
      @cancel="oncancel"
      @ok="onok"
    ></ksp-cropper>
    <view class="profile-picture" @click="myUpload">
      <uv-avatar
        :src="ImageAddHttp(avatar)"
        size="80"
        style="border-radius: 50%; width: 80px; height: 80px"
      ></uv-avatar>
      <view class="edit-picture">上传头像</view>
    </view>
    <view class="form-container">
      <view class="form-item">
        <text class="label">Nickname</text>
        <input v-model="nickname" class="input" placeholder="Nickname" />
      </view>

      <view class="form-item">
        <text class="label">Bio</text>
        <input v-model="bio" class="input" placeholder="Bio" />
      </view>
    </view>
    <view class="bottom-container">
      <uv-button type="primary" text="保存" @tap="onSubmit"></uv-button>
    </view>
  </view>
</template>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
  .profile-picture {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 50px;
    .edit-picture {
      margin-top: 10px;
      font-size: $uni-font-size-base;
      color: $uni-color-primary;
    }
  }
  .form-container {
    margin-top: 20px;
    padding: 10px;
    .form-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      border-bottom: 1px solid #e0e0e0;
      .label {
        width: 90px;
        color: $uni-color-subtitle;
      }
      .input {
        flex: 1;
        padding: 10px 0;
        border: none;
        outline: none;
        font-size: $uni-font-size-lg;
        color: $uni-text-color-placeholder;
      }
    }
  }

  .bottom-container {
    width: 90%;
    margin: 30rpx auto;
  }
}
</style>
